package com.yuanmei.views;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.yuanmei.datas.DBUtils;
import com.yuanmei.datas.FetchDataService;
import com.yuanmei.model.StockItem;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Locale;

public class BlockViewActivity extends AppCompatActivity
        implements View.OnClickListener, FetchDataService.MarketListener {
    private BlockListAdapter mBlockListAdapter;
    private FetchDataService.FetchDataBinder mFetchBinder;

    private static class MainViewMessageHandler extends Handler {
        private final WeakReference<BlockViewActivity> mWeakMainActivity;

        private MainViewMessageHandler(BlockViewActivity tvActivity) {
            mWeakMainActivity = new WeakReference<>(tvActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            BlockViewActivity tvActivity = mWeakMainActivity.get();
            if (tvActivity == null || msg.what > emHandleMessage.values().length) {
                return;
            }
            emHandleMessage type = emHandleMessage.values()[msg.what];
            switch (type) {
                case COMMON_NOTIFY_TOAST:
                    Toast.makeText(tvActivity, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    }

    private MainViewMessageHandler mMainMessagHandler;

    private enum emHandleMessage {
        COMMON_NOTIFY_TOAST,
    }

    private class FetchServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mFetchBinder = (FetchDataService.FetchDataBinder) service;
            mFetchBinder.registerMarketListener(BlockViewActivity.this);
            mFetchBinder.resetFetchList(mBlockListAdapter.getCurrentStockList());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mFetchBinder = null;
        }
    }

    private FetchServiceConnection mFetchServiceConnection;
    private String mStockIndustry;
    private String mStockArea;
    private TextView mTvStockNameHead;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_block_view);
        String stockName = getIntent().getStringExtra("Name");
        TextView tvStockName = findViewById(R.id.stock_name);
        tvStockName.setText(stockName);
        TextView tvStockCode = findViewById(R.id.stock_code);
        String stockCode = getIntent().getStringExtra("NetEaseCode");
        if (stockCode != null)
            tvStockCode.setText(stockCode.substring(1));

        mStockIndustry = getIntent().getStringExtra("Industry");
        mStockArea = getIntent().getStringExtra("Area");

        TextView tvBlockDetail = findViewById(R.id.block_detail);
        tvBlockDetail.setText(mStockIndustry + " " + mStockArea);

        RadioGroup blockGroup = findViewById(R.id.block_groups);

        blockGroup.clearCheck();
        RadioButton blockListRadioButton = findViewById(R.id.block_list_rb);
        blockListRadioButton.setChecked(true);
        blockGroup.setOnCheckedChangeListener((group, checkedId) -> onBlockGroupCheckedIdChanged(checkedId));

        mMainMessagHandler = new MainViewMessageHandler(this);

        ListView mBlockListView = findViewById(R.id.block_list);
        mBlockListAdapter = new BlockListAdapter(this, DBUtils.getIndustryList(mStockIndustry));
        mBlockListView.setAdapter(mBlockListAdapter);
        mBlockListView.setOnItemClickListener((a, v, position, id) -> startKLineActivity(position));

        mTvStockNameHead = findViewById(R.id.name_head);
        mTvStockNameHead.setOnClickListener(this);
        String head = String.format(Locale.CHINA, "股票 %d", mBlockListAdapter.getCount());
        mTvStockNameHead.setText(head);

        TextView stockPriceHead = findViewById(R.id.price_head);
        stockPriceHead.setOnClickListener(this);

        TextView stockVolumeHead = findViewById(R.id.volume_head);
        stockVolumeHead.setOnClickListener(this);

        TextView nprHead = findViewById(R.id.NPR_head);
        nprHead.setOnClickListener(this);

        TextView perHead = findViewById(R.id.PER_head);
        perHead.setOnClickListener(this);

        TextView industryHead = findViewById(R.id.industry_head);
        industryHead.setOnClickListener(this);

        Intent intent = new Intent(this, FetchDataService.class);
        mFetchServiceConnection = new FetchServiceConnection();
        bindService(intent, mFetchServiceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mFetchServiceConnection != null) {
            unbindService(mFetchServiceConnection);
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();         // Hide ActionBar
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.name_head:
                mBlockListAdapter.sortCurrentListByStockCode();
                break;
            case R.id.price_head:
                mBlockListAdapter.sortCurrentListByPricePercent();
                break;
            case R.id.volume_head:
                mBlockListAdapter.sortCurrentListByVolumePercent();
                break;
            case R.id.NPR_head:
                mBlockListAdapter.sortCurrentListByNetAssetsOperateProfitRatio();
                break;
            case R.id.PER_head:
                mBlockListAdapter.sortCurrentListByPriceEarningsRatio();
                break;
            case R.id.industry_head:
                mBlockListAdapter.sortCurrentListByIndustry();
                break;
            default:
                break;
        }
    }

    private boolean mIsActivityFront = false;

    @Override
    public void onResume() {
        super.onResume();
        mIsActivityFront = true;
        if (mFetchBinder != null)
            mFetchBinder.registerMarketListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        mIsActivityFront = false;
        if (mFetchBinder != null)
            mFetchBinder.unregisterMarketListener(this);
    }

    @Override
    public void onTodayQuotesFetched(ArrayList<String> quotesList) {
        int count = mBlockListAdapter.updateTodayQuotes(quotesList);
        if (mIsActivityFront) {
            notifyMessage("已更新 " + count + " 只股票的实时交易数据");
        }
        this.runOnUiThread(() -> mBlockListAdapter.notifyDataSetChanged());
    }

    @Override
    public void onTodayMinuteTickQuoteFetched(String neCode) {
        mBlockListAdapter.updateTodayMinuteTickQuote(neCode);
        this.runOnUiThread(() -> mBlockListAdapter.notifyDataSetChanged());
    }

    private void notifyMessage(String msg) {
        Message message = Message.obtain(mMainMessagHandler, emHandleMessage.COMMON_NOTIFY_TOAST.ordinal());
        message.obj = msg;
        message.sendToTarget();
    }

    private void startKLineActivity(int position) {
        Intent intent = new Intent(BlockViewActivity.this, KlineChartActivity.class);
        StockItem item = mBlockListAdapter.getItem(position);
        intent.putExtra("Name", item.name());
        intent.putExtra("NetEaseCode", item.netEaseCode());
        intent.putExtra("IsMarketIndex", item.isMarketIndex());
        intent.putExtra("FinanceInfo", item.getFinanceInfo());
        intent.putExtra("FinancialStatements", item.getFinancialStatements());
        intent.putExtra("MatchDetail", item.getMatchDetail());
        intent.putExtra("TodayOpen", item.getOpen());
        intent.putExtra("TodayPrice", item.getPrice());
        intent.putExtra("TodayHigh", item.getHigh());
        intent.putExtra("TodayLow", item.getLow());
        intent.putExtra("TodayYClose", item.getYestClose());
        if (item.isMarketIndex() && item.code().equalsIgnoreCase("000001")) {
            intent.putExtra("TodayVolume", item.getVolume() / 100);
        } else {
            intent.putExtra("TodayVolume", item.getVolume());
        }
        intent.putExtra("TodayAmount", item.getAmount());
        intent.putExtra("TodayIDate", item.getIDateOfUpdate());
        intent.putExtra("TodayBuys", item.getBuys());
        intent.putExtra("TodaySells", item.getSells());
        startActivity(intent);
    }

    private void onBlockGroupCheckedIdChanged(int checkedId) {
        switch (checkedId) {
            case R.id.block_list_rb:
                mBlockListAdapter.setCurrentStockList(DBUtils.getIndustryList(mStockIndustry));
                mBlockListAdapter.notifyDataSetChanged();
                if (mFetchBinder != null) {
                    mFetchBinder.resetFetchList(mBlockListAdapter.getCurrentStockList());
                }
                break;
            case R.id.area_list_rb:
                mBlockListAdapter.setCurrentStockList(DBUtils.getAreaList(mStockArea));
                mBlockListAdapter.notifyDataSetChanged();
                if (mFetchBinder != null) {
                    mFetchBinder.resetFetchList(mBlockListAdapter.getCurrentStockList());
                }
                break;
            default:
                break;
        }
        String head = String.format(Locale.CHINA, "股票 %d", mBlockListAdapter.getCount());
        mTvStockNameHead.setText(head);
    }
}
